package com.hanxiaozhang.redisson.source;

import io.netty.util.internal.PlatformDependent;
import org.redisson.QueueTransferTask;

import java.util.concurrent.ConcurrentMap;

/**
 * 功能描述: <br>
 * 〈源码阅读〉
 *
 * @Author: hanxinghua
 * @Date: 2022/9/19
 */
public class MyQueueTransferService {

    private final ConcurrentMap<String, MyQueueTransferTask> tasks = PlatformDependent.newConcurrentHashMap();

    public synchronized void schedule(String name, MyQueueTransferTask task) {
        MyQueueTransferTask oldTask = tasks.putIfAbsent(name, task);
        // 任务不存在，启动任务，否则使用次数+1
        if (oldTask == null) {
            task.start();
        } else {
            oldTask.incUsage();
        }
    }

    public synchronized void remove(String name) {
        MyQueueTransferTask task = tasks.get(name);
        if (task != null) {
            if (task.decUsage() == 0) {
                tasks.remove(name, task);
                task.stop();
            }
        }
    }


}
